/**
 * 手写签名
 * @author kaige
 * @date 2022-7-29
 * @version 1.0.0
 **/
layui.define(['layer', 'form', 'colorpicker'], function (exports) {
  var MOD_NAME = 'handlesign', $ = layui.jquery, form = layui.form, layer = layui.layer, colorpicker = layui.colorpicker;
  handlesign = function () { };

  handlesign.prototype.init = function (opt) {
    var t = this;
    //获得画布元素
    var canvas = document.getElementById(opt.elem);
    //获得二维绘图对象
    var ctx = canvas.getContext("2d");
    var ccolor = '#00aaff';
    initCanvas();
    //每次绘画重新开始
    canvas.onmousedown = function (e) {
      var e = e || window.event;
      ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
      document.onmousemove = function (e) {
        var e = e || window.event;
        ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
        ctx.stroke();
      };
      document.onmouseup = function () {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    };

    //每次绘画重新开始
    canvas.addEventListener("touchstart", function (e) {
      var x = e.changedTouches[0].clientX - e.target.offsetLeft;
      var y = e.changedTouches[0].clientY - e.target.offsetTop;
      ctx.beginPath();
      ctx.moveTo(x, y);

      canvas.addEventListener("touchmove", function (e) {
        e.preventDefault();
        var x = e.changedTouches[0].clientX - e.target.offsetLeft;
        var y = e.changedTouches[0].clientY - e.target.offsetTop;
        ctx.lineTo(x, y);
        ctx.stroke();
      }, false)
    }, false);

    colorpicker.render({
      elem: opt.lineColor
      , color: '#00aaff' //设置默认色
      , done: function (color) {
        ccolor = color;
        initCanvas();
      }
    });

    //画板初始化
    function initCanvas() {
      var obj = $(canvas).parent();
      canvas.width = obj.width();
      canvas.height = obj.height();
      //设置线宽
      ctx.lineWidth = '3';
      //线条颜色
      ctx.strokeStyle = ccolor || '#00aaff';
    }

    //重写签名
    $(opt.btn_reset).click(function () {
      initCanvas();
    })
    //生成
    $(opt.btn_create).click(function () {
      var reg = canvas.toDataURL("image/png"); //跳转页面手动保存
      typeof (opt.callback) === 'function' && opt.callback({ src: reg });
      // layer.alert(reg);
      //var reg=canvas.toDataURL("image/png").replace("image/png","image/octet-stream");//直接自动保存下载
      //location.href=reg;
    })
  };

  var handlesign = new handlesign();
  exports(MOD_NAME, handlesign)
});